// 获取投稿按钮和模态框
const uploadBtn = document.getElementById('uploadBtn');
const uploadModal = document.getElementById('uploadModal');
const closeBtn = document.querySelector('.close-btn');

// 打开投稿模态框
uploadBtn.addEventListener('click', function () {
    uploadModal.style.display = 'flex';
    document.body.style.overflow = 'hidden'; // 防止背景滚动
});

// 关闭投稿模态框
closeBtn.addEventListener('click', function () {
    uploadModal.style.display = 'none';
    document.body.style.overflow = 'auto'; // 恢复滚动
});

// 点击模态框外部关闭
window.addEventListener('click', function (event) {
    if (event.target === uploadModal) {
        uploadModal.style.display = 'none';
        document.body.style.overflow = 'auto'; // 恢复滚动
    }
});

// 文件上传区域交互效果
const fileUploads = document.querySelectorAll('.file-upload');
fileUploads.forEach(upload => {
    upload.addEventListener('dragover', function (e) {
        e.preventDefault();
        this.style.borderColor = '#00A1D6';
        this.style.backgroundColor = 'rgba(0, 161, 214, 0.1)';
    });

    upload.addEventListener('dragleave', function () {
        this.style.borderColor = '';
        this.style.backgroundColor = '';
    });

    upload.addEventListener('drop', function (e) {
        e.preventDefault();
        this.style.borderColor = '';
        this.style.backgroundColor = '';

        if (e.dataTransfer.files.length) {
            // 这里处理文件上传逻辑
            this.innerHTML = `<i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                                      <p>${e.dataTransfer.files[0].name}</p>
                                      <p class="small" style="color:#4CAF50;">上传成功</p>`;
        }
    });

});



//全局变量存储文件对象
let videoFile = null;
let coverFile = null;
let isFormSubmitInitialized = false;
let isNavigationInitialized = false;
let isModalInitialized = false;

//初始化文件上传区域
function initFileUploads() {
// 创建并缓存文件输入元素
const videoFileInput = document.getElementById('videoFileInput') || createFileInput('videoUpload');


const coverFileInput = document.getElementById('coverFileInput') || createFileInput('coverUpload');

// 获取上传区域
const videoUpload = document.getElementById('videoUpload');
const coverUpload = document.getElementById('coverUpload');

// 防止重复绑定事件
if (!videoUpload._initialized) {
    // 设置拖放功能
    setupDragDrop(videoUpload, videoFileInput, 'video');
    setupDragDrop(coverUpload, coverFileInput, 'image');
    
    // 设置点击功能
    videoUpload.addEventListener('click', () => videoFileInput.click());
    coverUpload.addEventListener('click', () => coverFileInput.click());
    
    // 监听文件选择变化
    videoFileInput.addEventListener('change', () => handleFileSelection(videoFileInput, videoUpload, 'video'));
    coverFileInput.addEventListener('change', () => handleFileSelection(coverFileInput, coverUpload, 'image'));
    
    // 标记为已初始化
    videoUpload._initialized = true;
    coverUpload._initialized = true;
}
}

//创建隐藏的文件输入元素
function createFileInput(id) {
const input = document.createElement('input');
input.type = 'file';
input.id = `${id}Input`;
input.style.display = 'none';
input.accept = id === 'videoUpload' ? 'video/*' : 'image/*';
document.body.appendChild(input);
return input;
}

//设置拖放功能
function setupDragDrop(uploadArea, fileInput, type) {
uploadArea.addEventListener('dragover', function(e) {
    e.preventDefault();
    this.style.borderColor = '#00A1D6';
    this.style.backgroundColor = 'rgba(0, 161, 214, 0.1)';
});

uploadArea.addEventListener('dragleave', function() {
    this.style.borderColor = '';
    this.style.backgroundColor = '';
});

uploadArea.addEventListener('drop', function(e) {
    e.preventDefault();
    this.style.borderColor = '';
    this.style.backgroundColor = '';

    if (e.dataTransfer.files.length) {
        fileInput.files = e.dataTransfer.files;
        handleFileSelection(fileInput, uploadArea, type);
    }
});
}

//处理文件选择
function handleFileSelection(fileInput, uploadArea, type) {
if (fileInput.files.length) {
    const file = fileInput.files[0];
    
    // 更新全局变量
    if (type === 'video') {
        videoFile = file;
        uploadArea.innerHTML = `
            <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
            <p>${file.name}</p>
            <p class="small">计算时长中...</p>
        `;
        getVideoDuration(file).then(duration => {
        	const durationInSeconds = Math.floor(duration);
            console.log('视频时长（秒）:', durationInSeconds);
            // 确保设置到隐藏字段
            document.getElementById('durationInSeconds').value = durationInSeconds;
            // 更新UI显示时长
            uploadArea.innerHTML = `
                <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                <p>${file.name}</p>
                <p class="small">时长: ${formatDuration(duration)}</p>
                <p class="small" style="color:#4CAF50;">视频已选择</p>
            `;
        }).catch(error => {
            console.error('获取视频时长失败:', error);
            document.getElementById('durationInSeconds').value = 0;
            uploadArea.innerHTML = `
                <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
                <p>${file.name}</p>
                <p class="small" style="color:#FF5722;">时长计算失败</p>
                <p class="small" style="color:#4CAF50;">视频已选择</p>
            `;   
        });
    } else {
    	coverFile = file;
    	uploadArea.innerHTML = `
            <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
            <p>${file.name}</p>
            <p class="small" style="color:#4CAF50;">封面已选择</p>
        `;
    }
    
    // 更新UI显示
    uploadArea.innerHTML = `
        <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
        <p>${file.name}</p>
        <p class="small" style="color:#4CAF50;">${type === 'video' ? '视频' : '封面'}已选择</p>
    `;
    
    // 重新绑定点击事件（因为innerHTML会移除原有的事件监听器）
    const fileInputEl = document.getElementById(`${uploadArea.id}Input`);
    uploadArea.addEventListener('click', () => fileInputEl.click());
}
}
function getVideoDuration(file) {
	return new Promise((resolve, reject) => {
    const video = document.createElement('video');
    const url = URL.createObjectURL(file);
    
    video.onloadedmetadata = () => {
        URL.revokeObjectURL(url); // 释放内存
        if (video.duration && video.duration > 0) {
            resolve(video.duration);
        } else {
            reject(new Error('无法获取有效视频时长'));
        }
    };
    
    video.onerror = () => {
        URL.revokeObjectURL(url);
        reject(new Error('视频加载失败'));
    };
    
    video.src = url;
    
    // 设置超时处理
    setTimeout(() => {
        if (video.readyState >= 1 && video.duration > 0) {
            URL.revokeObjectURL(url);
            resolve(video.duration);
        } else {
            URL.revokeObjectURL(url);
            reject(new Error('获取视频时长超时'));
        }
    }, 5000); // 5秒超时
});
}

//新增：格式化时长的函数
function formatDuration(seconds) {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);

if (h > 0) {
    return `${h}:${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
} else {
    return `${m}:${s.toString().padStart(2, '0')}`;
}
}

//初始化表单提交（防止重复绑定）
function initFormSubmit() {
if (isFormSubmitInitialized) return;

$(".btn-submit").off('click.submitHandler').on('click.submitHandler', function(e) {
    e.preventDefault();
    
    // 验证表单
    if (!videoFile) {
        alert('请选择视频文件');
        return;
    }
    
    // 确保获取时长值
    const durationInSeconds = document.getElementById('durationInSeconds').value || 0;
    
    const formData = new FormData();
    
    // 添加文本字段
    formData.append('videoTitle', $('#videoTitle').val());
    formData.append('videoDesc', $('#videoDesc').val());
    formData.append('videoCategory', $('#videoCategory').val());
    formData.append('durationInSeconds', durationInSeconds); // 明确添加时长字段
    
    // 添加文件
    formData.append('videoFile', videoFile);
    if (coverFile) formData.append('coverFile', coverFile);
    // 发送Ajax请求
    $.ajax({
        type: "POST",
        url: "createCenter.do",
        data: formData,
        contentType: false,
        processData: false,
        beforeSend: function() {
            $(".btn-submit").html('<i class="fas fa-spinner fa-spin"></i> 上传中...').prop('disabled', true);
        },
        success: function(data) {
            console.log("上传成功:", data);
            alert('投稿成功！');
            uploadModal.style.display = 'none';
            document.body.style.overflow = 'auto';
            resetUploadForm();
        },
        error: function(xhr, status, error) {
            console.error("上传失败:", error);
            alert('投稿失败：' + (xhr.responseJSON ? xhr.responseJSON.message : '网络错误'));
        },
        complete: function() {
            $(".btn-submit").html('发布投稿').prop('disabled', false);
        }
    });
});

isFormSubmitInitialized = true;
}

//重置上传表单
function resetUploadForm() {
videoFile = null;
coverFile = null;

// 重置UI显示
$('#videoUpload').html(`
    <i class="fas fa-cloud-upload-alt"></i>
    <p>点击或拖拽视频到此处</p>
    <p class="small">支持MP4、MOV、AVI等格式，最大2GB</p>
`);

$('#coverUpload').html(`
    <i class="fas fa-image"></i>
    <p>点击或拖拽封面到此处</p>
    <p class="small">支持JPG、PNG格式，建议尺寸1146x717</p>
`);

// 清空表单字段
$('#videoTitle').val('');
$('#videoDesc').val('');
$('#videoCategory').val('');
}

document.addEventListener('DOMContentLoaded', function() {
  console.log('DOMContentLoaded事件触发');
  initFileUploads();
  initFormSubmit();
});


// ----------------↑页面+投稿逻辑----------------↓ajax----------------

let currentPage = 1;

$("#selectAll").click(function(){
	$(".table-row input").prop("checked",this.checked)
})

$(".batch-btn").click(function(){
	let videoIdArray = []
	$(".table-row input[type='checkbox']").each(function(index){
		if($(this).prop("checked")){
			videoIdArray.push($(".col-title input[type='hidden']").eq(index).val())
		}
	})
	deleteVideos(videoIdArray)
	currentPage = 1
})


$(".videos-table").on("click",".action-btn",function(){
	if($(this).hasClass("delete")){
		deleteVideos($(this).parent().siblings("div.col-title").find("input").val())
		currentPage = 1
	}
})

$(".filter-select").each(function(){
	$(this).on("change", function() {
		currentPage = 1
		queryMyAllSendVideo()
	});
})
$(".search-container i").click(function(){
	currentPage = 1
	queryMyAllSendVideo()
})
queryMyAllSendVideo()
function queryMyAllSendVideo(pageNum = 1){
	let allVideo = $("#allVideo")
	let state = $(".filter-select").eq(0).val();
	let category = $(".filter-select").eq(1).val();
	let sortOrder = $(".filter-select").eq(2).val();
	let title = $(".search-container input").val();
	
	$.ajax({
		url:"queryMyAllSendVideo",
		type:"post",
		data:{
			pageNum:pageNum,
			state:state,
			sortOrder:sortOrder,
			title:title,
			category:category
		},
		success:function(data){
			allVideo.empty()
			if(data.code == 200){
				let videos = data.data.data
				for(let i = 0;i<videos.length;i++){
					let video = videos[i]
					let state = video.status
					let addClass;
					if(state == 0){
						state = "审核中"
						addClass = "status-review"
					}else{
						state = "已发布"
						addClass = "status-published"
					}
					let totalTime = countVideoTime(video.duration)
					let div = `
						<div class="table-row">
	                    <div class="col-checkbox">
	                        <input type="checkbox">
	                    </div>
	                    <div class="col-thumbnail">
	                        <div class="video-thumb">
	                        	<img src="${video.coverUrl}">
	                            <div class="video-duration">${totalTime}</div>
	                        </div>
	                    </div>
	                    <div class="col-title">
	                    	<input type="hidden" value="${video.videoId}">
	                        <div class="video-title">${video.title}</div>
	                        <div class="video-info">${video.name}区 · ${video.createTime} 发布</div>
	                    </div>
	                    <div class="col-status">
	                        <span class="status-badge ${addClass}">${state}</span>
	                    </div>
	                    <div class="col-stats">
	                        <div class="video-stats">
	                            <div class="stat-item"><i class="fas fa-play"></i>${video.viewCount}</div>
	                            <div class="stat-item"><i class="fas fa-comment"></i>${video.commentNum}</div>
	                            <div class="stat-item"><i class="fas fa-heart"></i>${video.likeCount}</div>
	                        </div>
	                    </div>
	                    <div class="col-actions">
	                        <button class="action-btn delete">删除</button>
	                    </div>
	                </div>
					`
					allVideo.append(div)
				}
				makePageBar(data.data)
				$(".pagination").css("display","flex")
			}else{
				let div = `
					<div style="width: 148px;margin: 17% auto;">
	                	<img src="img/ZFZJ.svg">
	                	<p style="text-align: center">没有找到哦~</p>
	                </div>
				`
					allVideo.append(div)
				$(".pagination").css("display","none")
			}
		}
	})
}

function countVideoTime(totalSecond){
	let hous = parseInt(totalSecond/60/60)
	let minute = parseInt((totalSecond - hous*60*60)/60)
	let second = totalSecond - hous*60*60 - minute*60
	if(hous < 10){
		hous = "0"+hous
	}
	if(minute < 10){
		minute = "0"+minute
	}
	if(second < 10){
		second = "0"+second
	}
	let totalTime;
	if(hous == 0){
		totalTime = minute+":"+second
	}else{
		totalTime = hous+":"+minute+":"+second
	}
	return totalTime;
}

function makePageBar(page) {
	$("#selectAll").prop("checked",false)
    let pageBar = $(".pagination");
    let navigatorNums = page.totalPageNum;
    pageBar.empty();

    if (page.hasPrev) {
        let prevPage = $("<div class='pagination-btn'><i class='fas fa-chevron-left'></i></div>").click(function() {
        	queryMyAllSendVideo(currentPage - 1);
            currentPage--
        });
        pageBar.append(prevPage);
    }
    
    for (let i = 0; i < navigatorNums.length; i++) {
        let num = navigatorNums[i];
        let pageLink = $("<div class='pagination-btn'>"+num+"</div>").click(function() {
        	queryMyAllSendVideo(num);
            currentPage = num 
        });
        if (num == currentPage) {
            pageLink.addClass("active");
        }
        pageBar.append(pageLink);
    }

    if (page.hasNext) {
        let nextPage = $("<div class='pagination-btn'><i class='fas fa-chevron-right'></i></div>").click(function() {
        	queryMyAllSendVideo(currentPage + 1);
            currentPage++
        });
        pageBar.append(nextPage);
    }
}


function deleteVideos(allVideoId){
	$.ajax({
		url:"deleteVideos",
		type:"post",
		traditional: true,
		data:{
			allVideoId:allVideoId
		},
		success:function(data){
			if(data.code == 200){
				promptAnimation("删除视频成功")
				queryMyAllSendVideo()
			}else{
				promptAnimation("删除视频失败")
			}
			
		}
	})
}

queryAllCategory()
function queryAllCategory(){
	let category = $(".filter-select").eq(1)
	let videoCategory = $("#videoCategory")
	$.ajax({
		url:"queryAllCategory",
		type:"post",
		success:function(data){
			if(data.code == 200){
				category.empty();
				videoCategory.empty();
				category.append($("<option>全部分区</option>"));
				videoCategory.append($("<option>选择视频分区</option>"))
				let allCategory = data.data
				for(let i = 0;i<allCategory.length;i++){
					let category_one = allCategory[i]
					let option = `
						<option>${category_one.name}</option>
					`
					category.append(option)
					videoCategory.append(option)
				}
			}
		}
	})
}

function promptAnimation(text) {
    let $prompt = $("#prompt");
    $prompt.text(text)
    // 确保元素回到初始位置
    $prompt.css("top", "-60px");
    
    // 上升动画
    $prompt.animate({ top: 0 }, {
        duration: 240,  // 60px / (5px/20ms) = 240ms
        easing: "linear",
        complete: function() {
            // 等待1秒后执行下降动画
            setTimeout(function() {
                // 下降动画
                $prompt.animate({ top: -60 }, {
                    duration: 240,
                    easing: "linear"
                });
            }, 1500);
        }
    });
}